import React, { PropTypes, Component } from 'react'
import fetch from 'isomorphic-fetch'
import { Link } from 'react-router'

import Table from './Table'
import NavLink from './NavLink'
import style from './addStore.css'
import './../css/default-select.css'

import { myAjax, ROOTURL_MALL } from '../publicAPI/publicAPI'

class MallProductsM extends Component {
	constructor (props, context) {
	    super(props, context)
	    console.log("初始化");

	    this.state = {
	    	page: 1,
	    	delete: false,
	    	deleteId: -1,
	        ProductData:[],
	        select_updown:'所有商品',
	        typeData:[],
	        typeBelong:'',
	        giftBelong:'',
	        select_show:'none',
	        select_show2:'none',
	        typeSelectId: -1,
	        giftSelectId: -1,
	    } ;// 初始化状态

	    this.handleGetTable(-1,-1);


		  var URL1 = ROOTURL_MALL +'kabuy/category/search.api';
	      var _this = this ;
	      fetch(URL1, {
	          method : 'POST',
	          mode: 'cors',
	          body: JSON.stringify({})
	      }).then(res=>{
	          if(res.ok){
	              res.json().then(data=>{
	                  for(var i=0;i<data.length;i++){
	                  	if(data[i].dd == false){
	                  		_this.state.typeData.push(<li data-id={data[i].id} onClick={(e) => this.inputTClick(e)}>{data[i].name}</li>)
	                  	}
	                  }
	              })
	          }
	      })
	}



	componentWillMount() {
	     console.log("将安装");
	}

	componentDidMount() {
	    console.log("安装成功");
	}

	handleDelete(id) {
		this.setState({
			delete: !this.state.delete,
			deleteId: id
		})
	}

	handleGetTable(categoryId,giftId){
	    var URL = ROOTURL_MALL +'kabuy/item/search.api';

    	var _this = this ;
    	var param = {}
    	var giftbool = null;
    	// alert(giftId)
    	if(giftId == 1){
    		giftbool = true;
    	}else if(giftId == 2){
    		giftbool = false;
    	}
    	if(categoryId!=(-1)){
    		param = {
    			"where": {
    				categoryId: [
    				    ["eq", categoryId]
    				]
    			}
    		}
    	}
        fetch(URL, {
            method : 'POST',
            mode: 'cors',
            body: JSON.stringify(param)
        }).then(res=>{
            if(res.ok){
                res.json().then(data=>{
                	// console.log('----------');
                    console.log(data.length);
                    // console.log('----------');
                    var data2 = [];
                    if(giftId==(-1)||giftId==(2)){
                    	for(var k=0; k<data.length; k++){
                    		if( !(data[k].dd)){
                    			data2.push(data[k]);
                    		}
                    	}
                    }else{
                    	for(var k=0; k<data.length; k++){
                    		if( (!(data[k].dd)) &&  (data[k].meta.gift )){
                    			data2.push(data[k]);
                    		}
                    	}
                    }

                    console.log(res);
                    _this.setState({
                       ProductData:data2
                    })
                })
            }
        })
	}

	inputFocus() {
	    this.setState({select_show: "block"})
	}
	inputFocus2() {
	    this.setState({select_show2: "block"})
	}

	inputTClick(e){
		const selectValue = e.target.innerText
		this.setState({
		  typeSelectId: e.target.getAttribute('data-id')
		})
		this.setState({select_show: "none", typeBelong: selectValue})
		this.handleGetTable(e.target.getAttribute('data-id'), this.state.giftSelectId);
	}
	inputTClick2(e){
		const selectValue = e.target.innerText
		this.setState({
		  giftSelectId: e.target.getAttribute('data-id')
		})
		this.setState({select_show2: "none", giftBelong: selectValue})
		// alert(this.state.typeSelectId);
		// alert(e.target.getAttribute('data-id'))
		this.handleGetTable(this.state.typeSelectId, e.target.getAttribute('data-id'));
	}

	updown_list(){
		var arr = [];
		arr.push((<option>所有商品</option>));
		arr.push((<option>点赞商品</option>));
		arr.push((<option>被踩商品</option>));
		return arr;
	}

	deleteType(id){
		var URL = ROOTURL_MALL +'kabuy/item/instance.api?id='+this.state.deleteId;
		var _this = this;
        fetch(URL, {
            method : 'DELETE',
            mode: "cors",
            headers: {
                 "Content-type": "application/json; charset=UTF-8"
             },
            body: {}
        }).then(res=>{
            if(res.ok){
                console.log('delete success');
	               var type = _this.state.ProductData;
	               _this.state.ProductData.map(function (result,index) {
	                   if(result.id == _this.state.deleteId){
	                       type.splice(index,1);
	                       _this.setState({
	                           ProductData: type
	                       })
	                   }
	               })

            }else{
            	console.log(res)
            }
        })
        this.setState({
	        delete: !this.state.delete
	    });
	}

	listSelect(val){




	}

	tHead() {
		var data = [
			{name: "id"},
			{name: "商品名"},
			{name: "所属分类"},
			{name: "价格"},
			{name: "原价"},
			{name: "赞"},
			{name: "踩"},
			{name: "月销量"},
			{name: "库存"},
			{name: "操作"}
		];
		const _headArr = [];
		const _width = {
			"0" : "5%",
			"1" : "30%",
			"2" : "10%",
			"3" : "7%",
			"4" : "7%",
			"5" : "5%",
			"6" : "5%",
			"7" : "5%",
			"8" : "5%",
			"9" : "20%",
		};
		//_headArr.push(<th style={{width:'5%'}} role="1" key='' onClick={(e) => this.handleSelect(e)}></th>)
		_headArr.push(data.map((item, index) => <th style={{width: _width[index]}} role="1" key={index}>{item.name}</th>))
		return _headArr;
	}

	tBody() {



		var _data = [


		];
		return this.state.ProductData.map(item => <tr key={item.id}>
					<td>{item.id}</td>
					<td>{item.name}</td>
					<td>{item.meta.typeName}</td>
					<td>{item.price ? item.price.toString() : '0' }</td>
					<td>{item.meta.initPrice ? item.meta.initPrice.toString() : '0'}</td>
					<td>{item.up}</td>
					<td>{item.down}</td>
					<td>{item.saleCounts}</td>
					<td>{item.stock}</td>
					<td>
						<span><NavLink  to={`/MallProductsM/MallProductsEditor/${item.id}`} className="rbtn green">查看</NavLink></span>
						<span style={{marginLeft: "15px"}}><a  className="rbtn red" onClick={() => this.handleDelete(item.id)}>删除</a></span>
					</td>
				</tr>)


	}

	render(){
		return (

			<div className="right-wapper ">
			    <div className="rt-wrap">
			        <h2 className="catagory">
			            <Link to={`/MallIndex`}><span className={style['cata-title']}>首页轮播图</span></Link>
			            <Link to={`/MallProductTypeM`}><span className={style['cata-title']}>商品分类管理</span></Link>
			            <Link to={`/MallProductsM`}><span className={style['cata-title-current']}>商品管理</span></Link>
			            <Link to={`/MallOrderM`}><span className={style['cata-title']}>订单管理</span></Link>
			            <Link to={`/MallStoreM`}><span className={style['cata-title']}>门店管理</span></Link>
			            <Link to={`/MallMember`}><span className={style['cata-title']}>门店店员管理</span></Link>
			            <Link to={`/MallStatisticsM`}><span className={style['cata-title']}>商城统计</span></Link>
			            <Link to={`/MallCoupon`}><span className={style['cata-title']}>优惠券管理</span></Link>
			            <Link to={`/MallProductsM/MallProductsEditor`}>
			                <button className="add-btn" />
			            </Link>
			        </h2>
			        <div style={{margin:'20px 0 5px'}}>
			        </div>
			        <div>
	        	        <div className={style["input_div"]} style={{position:'relative',float:'left'}}>
	        	            <label>所属分类</label>
	        	            <input inputId="typeBelong" className="default-text" placeholder="" value={this.state.typeBelong} readOnly onFocus={() => this.inputFocus()} onChange={val=>this.setState(Object.assign({},this.state, {typeBelong: val}))} style={{width:'140px '}}/>&nbsp;&nbsp;
	        	            <ul  className="input_select" style={{display: this.state.select_show,width:'156px'}}>
	        	             <li data-id="-1" onClick={(e) => this.inputTClick(e)}>(所有分类)</li>
	        	             {this.state.typeData}
	        	            </ul>
	        	        </div>
	        	        <div className={style["input_div"]} style={{position:'relative',float:'left'}}>
	        	            <label>有无优惠券</label>&nbsp;
	        	            <input inputId="giftBelong" className="default-text" placeholder="" value={this.state.giftBelong} readOnly onFocus={() => this.inputFocus2()} onChange={val=>this.setState(Object.assign({},this.state, {giftBelong: val}))} style={{width:'140px '}}/>&nbsp;&nbsp;
	        	            <ul  className="input_select" style={{display: this.state.select_show2,width:'156px', left:'85px'}}>
	        		             <li data-id="-1" onClick={(e) => this.inputTClick2(e)}>(有或无)</li>
	        		             <li data-id="1" onClick={(e) => this.inputTClick2(e)}>有</li>
	        		             <li data-id="2" onClick={(e) => this.inputTClick2(e)}>无</li>
	        	            </ul>
	        	        </div>
			        </div>


			        <Table tHead={this.tHead.bind(this)()} tBody={this.tBody.bind(this)()}/>
			    </div>


			    { this.state.delete ?
			    	<div id={style.msgDialog}>
			    		<div className={style['msgDialog_div']}><h3 id={style['msgDialog_title']}>删除提示？</h3><p id={style['msgDialog_content']}>确认删除？</p>
			    			<div className={style['msgDialog_button']}>
			    				<button id={style['msgDialog_yes']} onClick={this.deleteType.bind(this)}>确定</button>
			    				<button id={style['msgDialog_no']} onClick={()=>this.setState({delete: !this.state.delete})}>取消</button>
			    			</div>
			    		</div>
			    	</div> : null}
			</div>
		)
	}
}


export default MallProductsM
